<?php
    // +----------------------------------------------------------------------
    // | ThinkPHP [ WE CAN DO IT JUST THINK ]
    // +----------------------------------------------------------------------
    // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
    // +----------------------------------------------------------------------
    // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
    // +----------------------------------------------------------------------
    // | Author: 流年 <liu21st@gmail.com>
    // +----------------------------------------------------------------------

    use Jrk\Email;
    use Jrk\Times;
    use think\facade\Cache;
    use think\facade\Env;

    use think\Db;


    //加载额外的
    if (is_file(Env::get('app_path').'function.php')) {
        include_once Env::get('app_path').'function.php';
    }

    // 应用公共文件

    if (!function_exists('rm_empty_dir')) {
        /**
         * @param $path
         * @return bool
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/1/9
         * @name: rm_empty_dir
         * @describe:删除所有空目录
         */
        function rm_empty_dir($path)
        {
            if (!(is_dir($path) && ($handle = opendir($path)) !== false)) {
                return false;
            }
            while (($file = readdir($handle)) !== false) {
                if (!($file != '.' && $file != '..')) {
                    continue;
                }
                $curfile = $path.DS_PROS.$file;// 当前目录
                if (!is_dir($curfile)) {
                    continue;
                }
                rm_empty_dir($curfile);
                if (count(scandir($curfile)) == 2) {
                    rmdir($curfile);
                }
            }
            closedir($handle);
        }
    }


    if (!function_exists('hook')) {
        /**
         * @param $behavior
         * @param $params
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/1/9
         * @name: hook
         * @describe:钩子行为
         */
        function hooks($behavior, $params)
        {
            think\facade\Hook::exec($behavior, $params);
        }
    }

    if (!function_exists('get_addon_class')) {
        /**
         * @param $name
         * @param string $type
         * @param null $class
         * @return string
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/18
         * @name: get_addon_class
         * @describe:获取插件类的类名
         */
        function get_addon_class($name, $type = 'hook', $class = null)
        {
            $name = \think\Loader::parseName($name);
            // 处理多级控制器情况
            if (!is_null($class) && strpos($class, '.')) {
                $class = explode('.', $class);

                $class[count($class) - 1] = \think\Loader::parseName(end($class), 1);
                $class                    = implode('\\', $class);
            } else {
                $class = \think\Loader::parseName(is_null($class) ? $name : $class, 1);
            }

            switch ($type) {
                case 'controller':
                    $namespace = "\\addons\\".$name."\\controller\\".$class;
                    break;
                default:
                    $namespace = "\\addons\\".$name."\\".$class;
            }

            return class_exists($namespace) ? $namespace : '';
        }
    }


    if (!function_exists('get_addon_config')) {
        /**
         * 获取插件类的配置值值
         * @param string $name 插件名
         * @return array
         */
        function get_addon_config($name)
        {
            $addon = get_addon_instance($name);
            if (!$addon) {
                return [];
            }

            return $addon->getAddonConfig();
        }
    }


    if (!function_exists('get_addon_instance')) {
        /**
         * 获取插件的单例
         * @param $name
         * @return mixed|null
         */
        function get_addon_instance($name)
        {
            static $_addons = [];
            if (isset($_addons[$name])) {
                return $_addons[$name];
            }
            $class = get_addon_class($name);
            if (class_exists($class)) {
                $_addons[$name] = new $class();

                return $_addons[$name];
            } else {
                return null;
            }
        }
    }


    if (!function_exists('str2arr')) {
        /**
         * 字符串转换为数组，主要用于把分隔符调整到第二个参数
         * @param string $str 要分割的字符串
         * @param string $glue 分割符
         * @return array
         */
        function str2arr($str, $glue = ',')
        {
            return explode($glue, $str);
        }
    }


    if (!function_exists('arr2str')) {
        /**
         * 数组转换为字符串，主要用于把分隔符调整到第二个参数
         * @param array $arr 要连接的数组
         * @param string $glue 分割符
         * @return string
         */
        function arr2str($arr, $glue = ',')
        {
            if (is_string($arr)) {
                return $arr;
            }

            return implode($glue, $arr);
        }
    }

    if (!function_exists('int_to_string')) {
        /**
         * @param $data
         * @param array $map
         * @return array
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/18
         * @name: int_to_string
         * @describe:
         */
        function int_to_string(&$data, $map = ['status' => [1 => '正常', -1 => '删除', 0 => '禁用', 2 => '未审核', 3 => '草稿']])
        {
            if ($data === false || $data === null) {
                return $data;
            }
            $data = (array)$data;
            foreach ($data as $key => $row) {
                foreach ($map as $col => $pair) {
                    if (isset($row[$col]) && isset($pair[$row[$col]])) {
                        $data[$key][$col.'_text'] = $pair[$row[$col]];
                    }
                }
            }

            return $data;
        }
    }

    if (!function_exists('sendMaile')) {

        /**
         * @param $subject
         * @param $body
         * @param $to
         * @param null $attachment
         * @return array
         * @throws \PHPMailer\PHPMailer\Exception
         * @throws \think\Exception
         * @throws \think\exception\PDOException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/17
         * @name: sendMaile
         * @describe: 邮件发送
         */
        function sendMaile($subject, $body, $to, &$attachment = null)
        {
            $maile = Email::instance();
            $maile->subject($subject);
            $maile->body($body);
            $maile->to($to);

            if (isset($attachment) && !empty($attachment)) {
                if (is_array($attachment)) {
                    foreach ($attachment as $v) {
                        $maile->attachment($v);
                    }
                } else {
                    $maile->attachment($attachment);
                }
            }
            $result = $maile->send();
            if ($result) {
                $arr = ['code' => 1, 'msg' => '发送成功'];
            } else {
                $arr = ['code' => 0, 'msg' => $maile->getError()];
            }

            return $arr;
        }
    }


    if (!function_exists("formBytes")) {
        /**
         * @param $size
         * @param string $delimiter
         * @return string
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/1/9
         * @name: format_bytes
         * @describe:格式化数据
         */
        function formBytes($size, $delimiter = '')
        {
            $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
            for ($i = 0; $size >= 1024 && $i < 5; $i++) {
                $size /= 1024;
            }

            return round($size, 2).$delimiter.$units[$i];
        }
    }

    if (!function_exists("FriendTime")) {
        /**
         * @param $time
         * @return false|string
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/2/28
         * @name: FriendTime
         * @describe:时间友好
         */
        function FriendTime($time)
        {
            return Times::friendlyDate($time);
        }
    }

    if (!function_exists("clearCache")) {

        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/1/14
         * @name: clearCache
         * @describe:清除缓存
         */
        function clearCache()
        {
            Cache::clear();
        }
    }



    if (!function_exists('Logs')) {
        /**
         * @param $content
         * @param string $dir
         * @param string $file
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/12 0012
         * @name: Logs
         * @describe:记录日志文件
         */
        function Logs($content, $dir = 'jrk', $file = '')
        {
            if (empty($file)) {
                $file = date("Y_m_d", time());
            }
            $file_path = ROOT_PATH.'Logs/'.$dir;
            if (!is_dir($file_path)) {
                mkdir($file_path, 0777, true);
            }
            @file_put_contents(
                $file_path.'/'.$file.'.log',
                date('Y-m-d H:i:s', time()).' '.var_export($content, true)."\r\n",
                FILE_APPEND
            );
        }
    }


    if (!function_exists('addLog')) {

        /**
         * @param string $title
         * @param string $content
         * @throws \think\Exception
         * @throws \think\exception\PDOException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/12 0012
         * @name: addLog
         * @describe:添加日志
         */
        function addLog($title = '', $content = '')
        {
            $log  = new \app\admin\model\Logs();
            $safe = GetSysConfig("admin_log");
            if (isset($safe) && (int)$safe == 1) { //是否开启网站后台日志
                $log->setTitle($title);
                $log->setContent($content);
                $log->record();
            }
        }
    }


    if (!function_exists('GetSysConfig')) {
        /**
         * 设备或配置系统参数
         * @param string $name 参数名称
         * @return string|boolean
         * @throws \think\Exception
         * @throws \think\exception\PDOException
         */
        function GetSysConfig($name)
        {
            $key = md5(config('database.hostname').'#'.config('database.database').$name);
            if (Cache::has($key)) {
                $data = Cache::get($key);
            } else {
                $data = Db::name('setting')->where("key", "=", "{$name}")->value("value");
                Cache::set($key, $data, 180);
            }

            return $data;
        }
    }



    if (!function_exists('build_ueditor')) {
        /**
         * @param array $params
         * @return string
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/19
         * @name: build_ueditor
         * @describe:百度编辑器内容
         */
        function build_ueditor($params = array())
        {
            $name = isset($params['name']) ? $params['name'] : null;
            $theme = isset($params['theme']) ? $params['theme'] : 'normal';
            $content = isset($params['content']) ? $params['content'] : null;
            /* 指定使用哪种主题 */
            $themes = array(
                'normal' => "[   
           'fullscreen', 'source', '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'directionalityltr', 'directionalityrtl', 'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
            'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
            'simpleupload', 'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
            'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
            'print', 'preview', 'searchreplace', 'drafts', 'help'
       ]", 'simple' => " ['fullscreen', 'source', 'undo', 'redo', 'bold']",
            );
            switch ($theme) {
                case 'simple':
                    $theme_config = $themes['simple'];
                    break;
                case 'normal':
                    $theme_config = $themes['normal'];
                    break;
                default:
                    $theme_config = $themes['normal'];
                    break;
            }
            /* 配置界面语言 */
            switch (config('default_lang')) {
                case 'zh-cn':
                    $lang = '/plugs/ueditor/lang/zh-cn/zh-cn.js';
                    break;
                case 'en-us':
                    $lang =  '/plugs/ueditor/lang/en/en.js';
                    break;
                default:
                    $lang = '/plugs/ueditor/lang/zh-cn/zh-cn.js';
                    break;
            }
            $include_js = '<script type="text/javascript" charset="utf-8" src="/plugs/ueditor/ueditor.config.js"></script> <script type="text/javascript" charset="utf-8" src="/plugs/ueditor/ueditor.all.min.js""> </script><script type="text/javascript" charset="utf-8" src="' . $lang . '"></script>';
            $content = json_encode($content);
            $str = <<<EOT
$include_js
<script type="text/javascript">
var ue = UE.getEditor('{$name}',{
    toolbars:[{$theme_config}],
        });
    if($content){
ue.ready(function() {
       this.setContent($content);	
})
   }
</script>
EOT;
            return $str;
        }
    }




